package lia.searching;

import static lia.util.Utilities.buildIndexDir;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.QueryParser.Operator;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import static lia.util.Constants.*;

/**
 * From chapter 3
 * 
 * @author F.H Dragon(fhdargon@gmail.com)
 * @version 1.0 at 2011/08/16
 */
public class Fragments {

	/**
	 * open searcher
	 * 
	 * @throws IOException
	 */
	public void openSearcher() throws IOException{
		//build directory
		Directory dir = FSDirectory.open(new File(buildIndexDir("n")));
		//build index reader
		IndexReader ir = IndexReader.open(dir);
		//build index searcher
		@SuppressWarnings("unused")
		IndexSearcher is = new IndexSearcher(ir);
	}
	
	/**
	 * reopen reader
	 * 
	 * @throws IOException
	 */
	public void nrtReader() throws IOException{
		
		//build directory
		Directory dir = FSDirectory.open(new File(buildIndexDir("n")));
		//build index reader
		IndexReader ir = IndexReader.open(dir);
		@SuppressWarnings("unused")
		IndexSearcher is;
		//reopen index reader
		IndexReader newIR = ir.reopen();
		if(newIR != ir){
			ir.close();
			ir = newIR;
			is = new IndexSearcher(ir);
		}
	}
	
	/**
	 * query parser operator...
	 * 
	 * @throws IOException
	 */
	public void queryParserOperator() throws IOException{
		
		//build analyzer
		Analyzer analyzer = new SimpleAnalyzer(LUCENE_VERSION);
		//build query parser
		QueryParser parser = new QueryParser(LUCENE_VERSION, "contents", analyzer);
		parser.setDefaultOperator(Operator.OR);
	}
	
	/**
	 * test Searcher...
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings({ "unused", "null" })
	public void testSearchSigs() throws IOException{
		
		Query query = null;
		Filter filter = null;
		TopDocs hits;
		TopFieldDocs fieldHits;
		Sort sort = null;
		Collector collector = null;
		int n = 10;
		IndexSearcher is = null;
		
		hits = is.search(query, n);
		hits = is.search(query, filter, n);
		fieldHits = is.search(query, filter, n, sort);
		is.search(query, collector);
		is.search(query, filter, collector);
	}
}
